/*
	$Id: spartacus.js,v 1.29 2012-12-12 07:48:50 eike Exp $
	Arena Fighter Code
	Author: Eike, Team Spockholm & the rest of the team
	License: http://www.tldrlegal.com/l/CC-NC, read the full text here: http://creativecommons.org/licenses/by-nc/3.0/legalcode
	Note that this code may not be used in commercial scripts or applications
	Bugs/todo:
	x Show all powerups always
	x show correct powerups
	x Better control
	x Show stamina use
	x Levelup
	x Levelup-Popup
	x Start timer
	x Restartable
	x Attack-Matrix
	x Log total loot
	x Clean powerups
	x Errorhandling on join
	x Save settings
	x Config dynamic (open close, show/hide)
	x Healing timer
	x standings
	x improve loot log
	- Log to server
	- Brag
	- Use of Powerups
	- Custom arena join
*/

javascript:(function (){
	var version='Spartacus v0.92 beta',
	rev =  /,v \d+\.(\d+)\s201/.exec("$Id: spartacus.js,v 1.29 2012-12-12 07:48:50 eike Exp $")[1],
	spocklet='spartacus',
	debug = false,
	debuglogs=[],
	logs=[],
	loglines = 12,
	looted = {},
	run=true,
	spinner = '<img src="https://zyngapv.hs.llnwd.net/e6/mwfb/graphics/mw_loader_final_v2.gif" width=32 height=32 />',
	mafia_attack = imgurl('icon_mafia_attack_22x16_01.gif','22','16','Mafia Attack Strength'),
	mafia_defense = imgurl('icon_mafia_defense_22x16_01.gif','22','16','Mafia Defense Strength'),
	wslink,
	socke, // websocket
	currdata, // copy of data
	cmdqueue=[],
	meid, //me
	poweratt = false,
	poweruplist = {},
	playerinfo={},
	playerids={},
	starting_in,
	starting_in_counter,
	attmatrix={},
	stam_on_start,
	healed_in,
	healed_in_counter,
	restart_in,
	restart_in_counter,
	itemdatabase={},
	worstitems,
	stats = {},
	show_config = false;

	var powerups = {
		1:{name:"Stamina Refill",pic:"https://zynga1-a.akamaihd.net/mwfb/mwfb/graphics/big_item_staminarefill_01.png"},
		2:{name:"Arena Health Refill",pic:"https://zynga1-a.akamaihd.net/mwfb/mwfb/graphics/big_item_arenahealthrefill_01.png"},
		3:{name:"Meta Flair",pic:"https://zynga1-a.akamaihd.net/mwfb/mwfb/graphics/big_item_quartflair_01.png"},
		4:{name:"Pain Killer",pic:"https://zynga1-a.akamaihd.net/mwfb/mwfb/graphics/big_item_painkiller_01.png"},
		5:{name:"Kamikaze",pic:"https://zynga1-a.akamaihd.net/mwfb/mwfb/graphics/big_item_suckerpunch_01.png"},
		6:{name:"Drained",pic:"https://zynga1-a.akamaihd.net/mwfb/mwfb/graphics/big_item_drained_02.png"},
		7:{name:"Reflector",pic:"https://zynga1-a.akamaihd.net/mwfb/mwfb/graphics/big_item_reflector_01.png"}
	};

	var powerup_display = {
		1:3,
		2:4,
		3:7
	};
	
	var difficulty = [
		'Easy',
		'Normal',
		'Hard'
	];

	try {
		if (localStorage.getItem) {
			storage = localStorage;
		}
		else if (window.localStorage.getItem) {
			storage = window.localStorage;
		}
	}
	catch(storagefail) {}

	//setup the initial html
	var style = '<style type="text/css">'+
		'.messages {border: 1px solid #888888; margin-bottom: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-border-radius: 5px;}'+
		'.messages img{margin:0 3px;vertical-align:middle}'+
		'.messages input {border: 1px solid #888888; -moz-border-radius: 3px; border-radius: 3px; -webkit-border-radius: 2px;padding 0;background: #000; color: #FFF; width: 32px;}'+
		'#'+spocklet+'_loading { display:none; }'+
		'#'+spocklet+'_table td { padding:3px; }'+
		'#'+spocklet+'_attmatrix td { padding:3px; border: 1px solid grey; width:20px; text-align:center;}'+
		'#'+spocklet+'_attmatrix th { padding:3px; border: 1px solid white; width:20px; text-align:center;}'+
		'#'+spocklet+'_attmatrix { border: 1px solid white; }'+
		'.'+spocklet+'_usepowerup { cursor:pointer; }'+
		'.'+spocklet+'_conf { display:none; }'+
	'</style>';

	var logo = '<a href="http://www.spockholm.com/mafia/testing.php#" target="_blank"><img src="http://www.mafia-tools.com/uploads/banner-spockholm-mafia-tools.png#" alt="Spockholm Mafia Tools" title="Spockholm Mafia Tools" width="425" height="60" style="margin-bottom: 5px;" /></a>';

	var spocklet_html =
	'<div id="'+spocklet+'_main">'+
		style+
		'<table class="messages">'+
		'<tr><td colspan="3" align="center" style="text-align:center;">'+logo+'<br />'+
//			'&nbsp;<a href="http://www.spockholm.com/mafia/help.php#" id="'+spocklet+'_help" class="sexy_button_new short" target="_blank" title="Get help"><span><span>Help</span></span></a>'+
//			'&nbsp;<a href="#" id="'+spocklet+'_stop" class="sexy_button_new short orange" title="Stop"><span><span>Stop</span></span></a>'+
//			'&nbsp;<a href="#" id="'+spocklet+'_rewards" class="sexy_button_new short green" title="Rewards"><span><span>Rewards</span></span></a>'+
			'<a href="#" id="'+spocklet+'_config_toggle" class="sexy_button_new short black" title="Config"><span><span style="background: url(\'http://mwfb.static.zgncdn.com/mwfb/graphics/v3/icon_hammer_wrench.png\') no-repeat scroll 4px 50% transparent; padding-left: 30px;">Config</span></span></a> '+
			'<a href="http://www.spockholm.com/mafia/donate.php#'+spocklet+'" '+$i('donate')+' class="sexy_button_new short black" target="_blank" title="Like what we do? Donate to Team Spockholm"><span><span><span class="cash"></span>Donate</span></span></a>'+

			'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="good" title="Build: '+rev+'">'+version+'</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'+
			'&nbsp;<a href="#" id="'+spocklet+'_start" class="sexy_button_new short green" title="Start Spartacus, god of the arena"><span><span>Start</span></span></a>'+
			'&nbsp;<a href="#" id="'+spocklet+'_close" class="sexy_button_new short red" title="Close Spartacus, no more killing"><span><span>Close</span></span></a>'+
		'</td></tr>'+
		'<tr><td colspan="3"><hr /></td></tr>'+
		'<tr><td colspan="3"><span id="'+spocklet+'_loading">'+spinner+' loading data...</span></td></tr>'+
		'<tr '+$c('conf')+'><td colspan="3"><span style="background: url(\'http://mwfb.static.zgncdn.com/mwfb/graphics/v3/icon_hammer_wrench.png\') no-repeat scroll 4px 50% transparent; padding-left: 30px;">Configuration</span></td></tr>'+
		'<tr '+$c('conf')+'><td>Arena:</td><td colspan="2">'+
		'<select '+$i('arenatype')+'><option value="lw">100 Stamina</option><option value="hw">500 Stamina</option></select>'+
		'</td></tr>'+
		'<tr '+$c('conf')+'><td valign="top">Restart:</td><td colspan="2">'+
		'<label>Restart after finishing <input type="checkbox" id="'+spocklet+'_restart" /></label> '+
		'<span '+$i('show_min_stam')+'>when at least <input type="text" '+$i('min_stam_for_restart')+' value=0 /> stamina left</span><br />'+
		'<label>Restart when out of stamina: <input type="checkbox" id="'+spocklet+'_restart_stam" /><span '+$i('show_restart_stam')+'> after <input type="text" '+$i('restart_minutes')+' value="5" /> minutes.</label></span>'+
		'</td></tr>'+
		'<tr '+$c('conf')+'><td valign="top">Type of attack:</td><td colspan="2">'+
		'<label>Powerattack: <input type="checkbox" id="'+spocklet+'_powerattack" checked /></label> &nbsp; '+
		'Number of attacks: <input type="text" '+$i('numatt')+' value="3" title="Number of attacks to batch"/>'+
		'</td></tr>'+
		'<tr '+$c('conf')+'><td>Target to attack:</td><td colspan="2"><select '+$i('seltarget')+'>'+
		'<option value="lowhealth">Lowest health alive</option>'+
		'<option value="highhealth">Highest health</option>'+
		'<option value="mostpoints">Most points alive</option>'+
		'<option value="leastpoints">Least points alive</option>'+
		'<option value="mostrespect">Most respect alive</option>'+
		'<option value="leastrespect">Least respect alive</option>'+
		'</select></td></tr>'+
		'<tr '+$c('conf')+'><td>Stop attacking:</td><td colspan="2"><select '+$i('stopon')+'>'+
		'<option value="never">never (attack until stamina is gone)</option>'+
		'<option value="stop">now (do not attack)</option>'+
		'<option value="leading">when having the lead by a specific number of points</option>'+
		'<option value="staminaused">when specific amount of stamina used</option>'+
		'<option value="staminaleft">when specific amount of stamina left</option>'+
		'</select><span '+$i('show_stopon_value')+'> value: <input type="text" '+$i('stoponvalue')+' value="0" /></span></td></tr>'+
		//'<tr><td>Power-Ups:</td><td colspan="2"><span class="more_in">not yet implemented</span></td></tr>'+
		'<tr '+$c('conf')+'><td valign="top">Popups:</td><td colspan="2">'+
		'<label>Show Levelup-Popup: <input type="checkbox" id="'+spocklet+'_leveluppopup" checked /></label>'+
		'</td></tr>'+
		'<tr '+$c('conf')+'><td colspan="3"><hr /></td></tr>'+
		'<tr><td>Stage:</td><td colspan="2"><span '+$i('stage')+'>Not started</span></td></tr>'+
		'<tr><td>Time left:</td><td colspan="2"><span '+$i('timeleft')+'>0</span>s</td></tr>'+
		'<tr><td valign="top">Power-Ups<br /><span class="more_in">(Click to use)</span>:</td><td colspan="2" valign="top"><span '+$i('powerups')+'></span></td></tr>'+
		'<tr><td>Stamina:</td><td colspan="2"><span class="stamina" '+$i('me_st')+'>0</span>, next +10 in <span '+$i('me_sr')+'>0</span>s, used: <span class="stamina" '+$i('me_stused')+'>0</span></td></tr>'+
		'<tr><td>Health:</td><td colspan="2"><span class="health" '+$i('me_health')+'>100</span>% &nbsp; <span '+$i('healin')+'></span></td></tr>'+
		'<tr id="'+spocklet+'_strength_row" style="display:none;"><td>Strength:</td><td colspan="2"><span id="'+spocklet+'_strength_stats"></span></td></tr>'+
		'<tr><td valign="top"><a href="#" '+$i('toggleactions')+' title="Click to show/hide attack matrix">Actions:</a></td><td colspan="2"><span style="display:none;" '+$i('attmatrix_outer')+'></span></td></tr>'+
		'<tr><td valign="top">Playertable:</td><td colspan="2">'+
			'<table '+$i('table')+'>'+
			'<tr><th>Opponent</th><th>Info</th><th>Respect</th><th style="width:65px;">Health</th><th>Score</th><th>Powerups</th></tr>'+
			'<tr><td><span '+$i('name0')+'>Opponent 0</span></td><td><span '+$i('diff0')+' class="difficulty"></span></td><td><span '+$i('respect0')+' class="respect">0</span></td><td><span class="health" '+$i('health0')+'>0</span>%</td><td><span '+$i('score0')+'>0</span></td><td><span '+$i('pu0')+'></span></td></tr>'+
			'<tr><td><span '+$i('name1')+'>Opponent 1</span></td><td><span '+$i('diff1')+' class="difficulty"></span></td><td><span '+$i('respect1')+' class="respect">0</span></td><td><span class="health" '+$i('health1')+'>0</span>%</td><td><span '+$i('score1')+'>0</span></td><td><span '+$i('pu1')+'></span></td></tr>'+
			'<tr><td><span '+$i('name2')+'>Opponent 2</span></td><td><span '+$i('diff2')+' class="difficulty"></span></td><td><span '+$i('respect2')+' class="respect">0</span></td><td><span class="health" '+$i('health2')+'>0</span>%</td><td><span '+$i('score2')+'>0</span></td><td><span '+$i('pu2')+'></span></td></tr>'+
			'<tr><td><span '+$i('name3')+'>Opponent 3</span></td><td><span '+$i('diff3')+' class="difficulty"></span></td><td><span '+$i('respect3')+' class="respect">0</span></td><td><span class="health" '+$i('health3')+'>0</span>%</td><td><span '+$i('score3')+'>0</span></td><td><span '+$i('pu3')+'></span></td></tr>'+
			'<tr><td><span '+$i('name4')+'>Opponent 4</span></td><td><span '+$i('diff4')+' class="difficulty"></span></td><td><span '+$i('respect4')+' class="respect">0</span></td><td><span class="health" '+$i('health4')+'>0</span>%</td><td><span '+$i('score4')+'>0</span></td><td><span '+$i('pu4')+'></span></td></tr>'+
			'<tr><td><span '+$i('name5')+'>Opponent 5</span></td><td><span '+$i('diff5')+' class="difficulty"></span></td><td><span '+$i('respect5')+' class="respect">0</span></td><td><span class="health" '+$i('health5')+'>0</span>%</td><td><span '+$i('score5')+'>0</span></td><td><span '+$i('pu5')+'></span></td></tr>'+
//			'<tr><td><span '+$i('name6')+'>Opponent 6</span></td><td><span '+$i('diff6')+' class="difficulty"></span></td><td><span '+$i('respect6')+' class="respect">0</span></td><td><span class="health" '+$i('health6')+'>0</span>%</td><td><span '+$i('score6')+'>0</span></td><td><span '+$i('pu6')+'></span></td></tr>'+
//			'<tr><td><span '+$i('name7')+'>Opponent 7</span></td><td><span '+$i('diff7')+' class="difficulty"></span></td><td><span '+$i('respect7')+' class="respect">0</span></td><td><span class="health" '+$i('health7')+'>0</span>%</td><td><span '+$i('score7')+'>0</span></td><td><span '+$i('pu7')+'></span></td></tr>'+
			'</table>'+
		'</td></tr>'+
		'<tr><td valign="top"><a href="#" '+$i('toggleloot')+' title="Click to show/hide loot log">Loot Log:</a></td><td colspan="2" '+$i('lootlog')+' style="display:none;"></td></tr>'+
//		'<a href="#" class="'+spocklet+'_att" data-id=0>att0</a> <a href="#" class="'+spocklet+'_att" data-id=1>att1</a> <a href="#" class="'+spocklet+'_att" data-id=2>att2</a> <a href="#" class="'+spocklet+'_att" data-id=3>att3</a> <a href="#" class="'+spocklet+'_att" data-id=4>att4</a> <a href="#" class="'+spocklet+'_att" data-id=5>att5</a> <a href="#" id="'+spocklet+'_paon">pa on</a> <a href="#" id="'+spocklet+'_paoff">pa off</a> '+
		'<tr><td colspan="3"><span id="'+spocklet+'_log"></span></td></tr>'+
		'<tr><td colspan="3"><hr /></td></tr>'+
		'<tr><td colspan="3"><span id="'+spocklet+'_debug" style="display:none;">Debug-Output</span></td></tr>'+
		'</table>'+
	'</div>';

	function create_div() {
		//setup the spockdiv
		if ($('#'+spocklet+'_main').length == 0) {
			$('#inner_page').before(spocklet_html);
			var pos = $('#'+spocklet+'_main').position();
			$('#'+spocklet+'_main').prepend('<a href="#" id="'+spocklet+'_debug_toggle"><img src="https://zynga1-a.akamaihd.net/mwfb/mwfb/graphics/clan/perks/Grenade3.png" width="2" height="2" style="position: absolute; left:'+parseInt(pos.left+7)+'px; top: '+parseInt(pos.top+7)+'px;" alt="Show/Hide stats" title="Show/Hide stats" /></a>');
		}
		else {
			//$('#'+spocklet+'_log').html();
		}
	}

	//http://facebook.mafiawars.zynga.com/mwfb/remote/html_server.php?xw_controller=Arena&xw_action=getSingleUserData&xw_city=&tmp=040adf77f458e931876a0ba39a09f6eb&cb=404bd4603e0911e2859f35370e016008&xw_person=&pid=146845412&xw_client_id=8

	function create_handler(){
		$e('close').click(function(){
			run = false;
			$e('main').remove();
			socke.close();
			return false;
		});
		$e('start').click(function(){
			run = true;
			join_arena();
			return false;
		});
		$e('rewards').click(function(){
			get_rewards(function(){});
			return false;
		});
		$e('debug_toggle').click(function(){
			debug=!debug;
			if(debug) {
				$e('debug').show();
			} else {
				$e('debug').hide();
			}
			return false;
		});
		$('.'+spocklet+'_att').click(function(){
			attack($(this).attr('data-id'),1);
			return false;
		});
		$e('toggleactions').click(function(){
			$e('attmatrix_outer').toggle(10);
			return false;
		});
		$e('toggleloot').click(function(){
			$e('lootlog').toggle();
			write_loot();
			return false;
		});
		/* toggles for config */
		load_config();

		$e('config_toggle').click(function(){
			if(!show_config) {
				$('.'+spocklet+'_conf').show();
				$(this).addClass('green').removeClass('black');
			}
			else {
				$('.'+spocklet+'_conf').hide();
				$(this).addClass('black').removeClass('green');
			}
			show_config=!show_config;
			return false;
		});
		$e('restart').change(function(){
			if(this.checked) {
				$e('show_min_stam').show();
			} else {
				$e('show_min_stam').hide();
			}
		}).trigger('change');
		$e('restart_stam').change(function(){
			if(this.checked) {
				$e('show_restart_stam').show();
			} else {
				$e('show_restart_stam').hide();
			}
		}).trigger('change');
		$e('stopon').change(function(){
			if(this.selectedIndex>1) {
				$e('show_stopon_value').show();
			} else {
				$e('show_stopon_value').hide();
			}


		}).trigger('change');
		$('.'+spocklet+'_conf input,select').change(function(){
			save_config();
		});

		//$e('paon').click(poweratt_on);
		//$e('paoff').click(poweratt_off);
	}

	create_div();
	create_handler();
	loadStats(); // mafia att, def and inventory


	/****************** connection functions ****************/
	function join_arena() {
		//check if Spartacus is still running
		if ($('#'+spocklet+'_main').length == 0) {
			return;
		}

		/* initialize vars */
		cmdqueue=[];
		meid=null;
		poweratt = false;
		poweruplist = {};
		playerinfo={};
		playerids={};
		attmatrix={};
		stam_on_start = null;
		$('span[id*="'+spocklet+'_pu"]').html('');
		$('span[id*="'+spocklet+'_name"]').html('');
		$e('attmatrix').remove();
		/* join */
		log('Joining arena...');
		var type = $e('arenatype').val();
		request('xw_controller=Lobby&xw_action=join_arena&arenaType='+type+'&xw_client_id=8',function(msg){
			//console.log(msg);
			json = JSON.parse(msg);
			if(json.data.success == 1) {
				log('Successfully joined Arena.');
				load_arena();
			}
			else {
				if (json.data.message.indexOf('Refresh to claim your rewards from the previous Arena')!=-1) {
					get_rewards();
				}
				else if(json.data.message.indexOf('have enough stamina to join this arena')!=-1) {
					log('Not enough Stamina, stopping.');
					if($e('restart_stam').is(':checked')) {
						var min=parseInt($e('restart_minutes').val());
						restart_in=unix_timestamp()+(min*60);
						log('Restarting in '+min+' minutes');
						restart_in_counter = setInterval(function(){
							if(unix_timestamp()>restart_in) {
								clearInterval(restart_in_counter);
								join_arena();
							} else {
								$e('timeleft').html('Restart in '+(restart_in-unix_timestamp()));
							}
						},1000);
						//timer
					}
				}
				else if(json.data.message.indexOf('Unable to join')!=-1) {
					var wait = Math.floor(Math.round((Math.random() * 8))+2);
					log('Unable to join this Arena. Join another one. Trying again in '+wait+'s...');
					setTimeout(join_arena,wait*1000);
				}
				else {
					log('Could not join, msg='+json.data.message);
				}
			}

		},function(){
			log('Error on trying to join');
			// script ends here
		});
	}

	function load_arena(){
		request('xw_controller=Lobby&xw_action=loadArena&xw_client_id=8',function(msg){
			var m;
			if(m = /viewObj.init\(\"([^\"]*)\",/.exec(msg)) {
				wslink = m[1];
				connect_arena(wslink);
			}
		},function(){
			log('Error on trying to load');
		});
	}

	function connect_arena(sockenurl) {
		socke=new WebSocket(sockenurl);
		socke.onopen=function(){
			log('Connected to Arena.');
		};
		socke.onmessage=function(msg){
//			log('Received:'+msg.data);
			json=JSON.parse(msg.data);
			update_info(json);
			decide_actions();
			send_queue();
		};
		socke.onclose=function(){
			//log('Disconnected');
			get_rewards();
		};
	}

	/******************* behavior logic ********************/
	function am_i_leading_by(points) {
		var best_player_points=0;
		for(var i in currdata.pi) {
			if(i!=meid) {
				if(currdata.pi[i].sc>best_player_points) { best_player_points=currdata.pi[i].sc;}
			}
		}
		var my_score=currdata.pi[meid].sc;
		//debuglog('My score: '+my_score+', BP score: '+best_player_points+', hence :'+(my_score-points>best_player_points));
		return my_score-points>best_player_points;
	}

	function decide_allowed_to_attack(){
		var stopon = $e('stopon').val();
		var stoponval = parseInt($e('stoponvalue').val());
		var stamused = stam_on_start-currdata.mi.st;

		if(currdata.pi[meid].ph==0) { return false; } // me dead
		if(currdata.mi.st<10) { return false; } // no stam
		if((currdata.mi.st<50) && (poweratt)) { return false; } // no stam
		switch(stopon) {
			case "never": return true;
			case "stop": return false;
			case "leading": return !am_i_leading_by(stoponval);
			case "staminaused": return stamused<stoponval;
			case "staminaleft": return currdata.mi.st>stoponval;
		}
		return true;
	}

	function decide_who_to_attack(){
		var target=$e('seltarget').val();
		var bestid=-1,best=0;
		for(var i in currdata.pi) {
			if(i!=meid) {
				if((currdata.pi[i].ph>0)) {
					var val;
					switch(target) {
						case "lowhealth": val=100-currdata.pi[i].ph; break;
						case "highhealth": val=currdata.pi[i].ph; break;
						case "lestpoints": val=1000000-currdata.pi[i].sc; break;
						case "mostpoints": val=currdata.pi[i].sc;break;
						case "leastrespect": val=10000-playerinfo[i].respect; break;
						case "mostrespect": val=playerinfo[i].respect; break;
					}
					if(val>best) { bestid=i; best=val; }
				}
			}
		}
		return bestid;
	}

	function decide_actions(){
		var numatt = parseInt($e('numatt').val()) || 3;
		if(currdata.s==2) { // fight active
			if($e('powerattack').is(':checked')) {
				poweratt_on();
			} else {
				poweratt_off();
			}
			if(decide_allowed_to_attack()) {
				var who=decide_who_to_attack();
				if (who!=-1) {
					attack(who,numatt);
				}
			}
		}
	}

	/********************* communication and stats ***********************/
	function get_rewards(handler) {
		// log('Retrieving rewards...');
		request('xw_controller=Arena&xw_action=rewards&xw_client_id=8',function(msg){
			parse_loot(msg);
			setTimeout(function(){ getStats(displayMafiaStats); },2000);
			if($e('restart').is(':checked')) {
				if(currdata.mi.st>=parseInt($e('min_stam_for_restart').val())) {
					join_arena();
				}
			}
		});
	}

	function parse_loot(msg){
		window.eikea=msg;
		$msg=$('<div>'+msg+'</div>');
		var rewards={};
		rewards.xp=parseInt($msg.find('.xp_earned > .value').text());
		rewards.respect=parseInt($msg.find('.respect_earned > .value').text());
		rewards.stam_cur=parseInt($msg.find('.stamina_stats > .current').text());
		rewards.stam_total=parseInt($msg.find('.stamina_stats > span:last').text());
		rewards.rank=$msg.find('.rank_holder > .position').text();
		rewards.ratio=(rewards.xp / (stam_on_start - currdata.mi.st + 50)).toFixed(2);
		rewards.loot=[];
		var loot_strings=[];
		$($msg.find('#your_reward_list > .arena_fight_rewards_item_container')).each(function(){
			var loot = {};
			loot.name = $(this).find('.arena_reward_items_bg > .name').text().trim();
			loot.id = $(this).find('.arena_reward_items_bg img').attr('item_id') || false;
			loot.src = $(this).find('.arena_reward_items_bg img').attr('src');
			loot.quantity = parseInt($(this).find('.qty').text().trim().substr(2));
			loot.attack = parseInt($(this).find('.attack').text().trim()) || 0;
			loot.defense = parseInt($(this).find('.defense').text().trim()) || 0;
			rewards.loot.push(loot);
			loot_strings.push('<img src="'+loot.src+'" class="item_with_preview" item_id="'+loot.id+'" width="16" height="16">'+loot.name+' <span class="good">&times;'+loot.quantity+'</span> ');
			add_loot(loot);
		});
		log('Result: '+rewards.rank+' Place: <span class="experience">'+rewards.xp+' ('+rewards.ratio+')</span> <span class="respect">'+(rewards.respect>0?'+':'')+rewards.respect+'</span> '+loot_strings.join(''));
		write_loot();

		var logline='Results: ';
		$($msg.find('.standings_list')).each(function(){
			var pos=$(this).find('.pos').text();
			var name=$(this).find('.name').text();
			var resp=$(this).find('.respect_wrapper').html();
			var powerups='';
			$(this).find('.powerups_used img').each(function(){
				powerups+='<img src="'+this.src+'" width=16 height=16 />';
			});
			logline+=pos+'. '+name+' <span class="respect">'+resp+'</span> '+powerups+' ';
		});
		log(logline);

		if(msg.indexOf('You are now LEVEL')!=-1) {
			log('<span class="good">Levelup!</span>');
			if($e('leveluppopup').is(':checked')) {
				var code=msg.re('(setTimeout.*\\,\\s10\\)\\;)');
				eval(code);
			}
		}

	}

	function add_loot(item) {
		var id = (Util.isset(item.id) ? item.id : item.name);
		if (typeof looted[id] == 'object') {
			looted[id].quantity += item.quantity;
		}
		else {
			looted[id] = {
				"id": id, "name": item.name, "src": item.src, "quantity": item.quantity, "attack":item.attack, "defense":item.defense
			}
		}
	}

	function sort_loot(){
		var list = [];
		for (var x in looted) {
			list.push(x);
		}
		list.sort(function(a,b){
			if(looted[a].name=="Ices") { return -1; }
			if(looted[b].name=="Ices") { return 1; }
			return compare(max(looted[a].attack,looted[a].defense),max(looted[b].attack,looted[b].defense));
		});
		return list;
	}

	function write_loot() {
		var sorted=sort_loot();
		var loothtml = '<table>';
		for (i=0;i<sorted.length;i++) {
			var loot = looted[sorted[i]];
			var image = '<img src="'+loot.src+'" class="item_with_preview" item_id="'+loot.id+'" title="'+loot.name+'" width="16" height="16" />';
			if (itemdatabase[loot.id]) {
				loot2 = itemdatabase[loot.id];
				var attack = '', defense = '', improves = false, improve = '';
				if (loot2.attack > 0) {
					attack = '['+loot2.attack+'A';
					if(worstitems[itemdatabase[loot.id].type].att<loot2.attack) {
						improves = true;
						improve += '<span class="attack good">+'+(loot2.attack - worstitems[itemdatabase[loot.id].type].att)+'</span> ';
					}
				}
				if (loot2.defense > 0) {
					defense = loot2.defense+'D]';
					if(worstitems[itemdatabase[loot.id].type].def<loot2.defense) {
						improves = true;
						improve += '<span class="defense good">+'+(loot2.defense - worstitems[itemdatabase[loot.id].type].def)+'</span>';
					}
				}
				var have = loot.quantity;

				have = (loot2.quantity>0?' <span class="more_in">Have: '+(loot2.quantity+loot.quantity)+'</span>':'');
				loothtml += '<tr><td><span class="good">&times;'+loot.quantity+'</span></td><td>'+image+'<span style="'+(improves?"color:yellow;":"")+'">'+loot2.name+'</td><td>'+attack+'</td><td>'+defense+'</span></td><td>'+improve+'</td><td>'+have+'</td></tr>';
			}
			else
			{
				if(loot.name=="Ices") {
					loothtml += '<tr><td><span class="good">&times;'+loot.quantity+'</span></td></td><td><span style="color: #609AD1; font-weight:bold;">'+image+loot.name+'</span></td><td></tr>';
				} else {
					loothtml += '<tr><td><span class="good">&times;'+loot.quantity+'</span></td></td><td>'+image+loot.name+'</td><td></tr>';
				}
			}
		}
		loothtml += '</table>';
		$e('lootlog').html(loothtml);
	}


	function get_stage(i) {
		if(i==1) { return "Waiting for Start"; }
		if(i==2) { return "Fighting"; }
		if(i==3) { return "Finished"; }
		return "Unknown";
	}

	function send_queue() {
		if(cmdqueue.length>0) {
			/* only debug */
			if(debug) {
				var debugstr='Send:';
				for(var i=0;i<cmdqueue.length;i++) {
					var cmd=cmdqueue[i].split(':');
					if(cmd[0]=="1") { debugstr+=' Attack #'+cmd[1]; }
					if(cmd[0]=="2") { debugstr+=' Poweratt '+cmd[1]; }
					if(cmd[0]=="3") { debugstr+=' Powerup '+powerups[cmd[1]].name; }
				}
				log(debugstr);
			}
			/* only debug end */
			var string='{"Nonce":'+currdata.mi.ammo+',"CMD":"'+cmdqueue.join(';')+'"}'
			cmdqueue=[];
			socke.send(string);
			//log("Send: "+string);
		}
	}

	function attack(i,num) {
		for(var j=0;j<num;j++) {
			cmdqueue.push("1:"+i);
		}
	}

	function poweratt_on() {
		if(!poweratt) {
			cmdqueue.push("2:1");
			poweratt=true;
		}
	}

	function poweratt_off() {
		if(poweratt) {
			cmdqueue.push("2:0");
			poweratt=false;
		}
		return false
	}

	function display_matrix(){
		var ts=unix_timestamp();
		if($e('attmatrix').length==0) {
			var html='<table '+$i('attmatrix')+' cellspacing=0 cellpadding=0><tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th><th>6</th>';
			for(var i=0;i<6;i++) {
				html+='<tr><th>'+(i+1)+'</th>';
				for(var j=0;j<6;j++) {
					html+='<td '+$i('mat_'+i+'_'+j)+'>'+(i==j?'':0)+'</td>';
				}
				html+='</tr>';
			}
			html+='</table>';
			$e('attmatrix_outer').html(html);
		}
		for(var i in attmatrix) {
			for(var j in attmatrix[i]) {
				$e('mat_'+i+'_'+j).html(attmatrix[i][j].count).css('background-color',(ts-attmatrix[i][j].lastupdate<2?'red':'black'));
			}
		}
	}

	function update_info(data) {
		// debuglog(JSON.stringify(data));
		// console.log(data);
		$e('timeleft').html(data.t);

		// counter
		if(data.s==1) {
			starting_in = unix_timestamp()+data.t;
			clearInterval(starting_in_counter) ;
			starting_in_counter = setInterval(function(){
				$e('timeleft').html(starting_in - unix_timestamp());
			},1000);
			if(data.mi) {
				stam_on_start = data.mi.st; // save at start
			}
		}
		else {
			clearInterval(starting_in_counter);
		}

		$e('stage').html(get_stage(data.s));

		// $e('ac').html(data.ac); boring old stuff
		// amazing new stuff: attack matrix
		if(data.ac) {
			var attacks=data.ac.split(';');
			var ts=unix_timestamp();

			for(var i=0;i<attacks.length;i++) {
				var attacker_defender=attacks[i].split(':');
				var att=attacker_defender[0],def=attacker_defender[1];

				if(!attmatrix[att]) {
					attmatrix[att]={};
				}
				if(!attmatrix[att][def]) {
					attmatrix[att][def]={ count:1, lastupdate:ts};
				}
				else {
					attmatrix[att][def].count++;
					attmatrix[att][def].lastupdate=ts;
				}
			}
			//console.log(attmatrix);
			display_matrix();
		}



		// enemy powerups
		for(var i in data.pi) {
			pi=data.pi[i];
			$e('health'+i).html(pi.ph);
			$e('score'+i).html(pi.sc);
			if(pi.pu>0) {
				if(pi.pu!=currdata.pi[i].pu) {
					$e('pu'+i).append('<img src="'+powerups[powerup_display[pi.pu]].pic+'" title="'+powerups[powerup_display[pi.pu]].name+'" width=22" height="22" /> ');
				}
			}
		}
		if(data.mi) {
			$e('me_st').html(data.mi.st);
			//$e('me_ammo').html(data.mi.ammo);
//			$e('me_pst').html(data.mi.pst);
			if(data.mi.pui) {
				update_powerups(data.mi.pui);
			}
			$e('me_sr').html(data.mi.sr);

			if(currdata && currdata.mi) {
				if(data.mi.st>currdata.mi.stam+11) { // used used a stam refill
					stam_on_start += (data.mi.st-currdata.mi.stam);
				}
			}
			$e('me_stused').html(stam_on_start - data.mi.st);
		}

		// healing timer
		if(meid) {
			$e('me_health').removeClass('good').removeClass('bad').addClass(data.pi[meid].ph>0?'good':'bad').html(data.pi[meid].ph);
			if((data.pi[meid].ph==0) && (currdata.pi[meid].ph>0)) {
				healed_in=unix_timestamp()+10;
				clearInterval(healed_in_counter);
				healed_in_counter = setInterval(function(){
					if(unix_timestamp()>healed_in) {
						clearInterval(healed_in_counter);
						$e('healin').html('');
					} else {
						$e('healin').html('Healing in '+(healed_in - unix_timestamp())+'s');
					}
				},1000);
			}
		}


		for(var i in data.pi) {
			if((data.pi[i].pid) && (!playerids[data.pi[i].pid])) {
				playerinfo[i]={ id:data.pi[i].pid };
				playerids[data.pi[i].pid]=i;
				if(data.pi[i].pid==User.id.substr(2)) {
					meid=i;
				}

				request('xw_controller=Arena&xw_action=getSingleUserData&pid='+data.pi[i].pid+'&xw_client_id=8',function(msg){
					var json=JSON.parse(msg);
					for(var id in json.data.result) {
						var nr=playerids[id];
						playerinfo[nr].name=json.data.result[id].fullName;
						playerinfo[nr].respect=json.data.result[id].playerRespect.replace(',','');
						playerinfo[nr].diff=difficulty[json.data.result[id].defenseFlag+json.data.result[id].mafiaDefenseFlag];
						if(id == User.id.substr(2)) {
							$e('name'+nr).html('<img src="'+json.data.result[id].pic+'" width="32" height="32" /><span class="good">Me!</span>');
						}
						else {
							var m;
							if(m=/\d+_(\d+)_\d+/.exec(json.data.result[id].pic)) {
								$e('name'+nr).html('<a href="https://www.facebook.com/'+m[1]+'" target="_blank"><img src="'+json.data.result[id].pic+'" width="32" height="32" />'+playerinfo[nr].name+'</a>');
							} else {
								$e('name'+nr).html('<img src="'+json.data.result[id].pic+'" width="32" height="32" />'+playerinfo[nr].name);
							}
						}
						$e('respect'+nr).html(playerinfo[nr].respect);
						$e('diff'+nr).html('<div class="difficulty">'+playerinfo[nr].diff+'</div>');
					}
				});
			}
		}
		currdata=data;
	}

	function update_powerups(pui) {
		var html='';
		var pups=pui.split('|');
		for(var i=0;i<pups.length;i++) {
			pup=pups[i].split(',');
			poweruplist[pup[0]]={ num:pup[2],cooldown:pup[1] }
		}
		for(var i in powerups) {
			html+=' <img class="'+spocklet+'_usepowerup" data-id="'+i+'" src="'+powerups[i].pic+'" title="'+powerups[i].name+'" width="30" height="30" /> &times'+poweruplist[i].num;
			if(poweruplist[i].cooldown>0) { html+=' (Active: '+poweruplist[i].cooldown+'s)'; }
		}
		$e('powerups').html(html);
		$('.'+spocklet+'_usepowerup').click(function(){
			var id=$(this).attr('data-id');
			cmdqueue.push('3:'+id);
			return false;
		});
	}
	/******************** config ********************/
	function save_config(){
		var config={};
		$('.'+spocklet+'_conf input[type=text]').each(function(){
			config[this.id.replace(spocklet,'')]=$(this).val();
		});
		$('.'+spocklet+'_conf input[type=checkbox]').each(function(){
			config[this.id.replace(spocklet,'')]=this.checked;
		});
		$('.'+spocklet+'_conf select').each(function(){
			config[this.id.replace(spocklet,'')]=$(this).val();
		});
		// console.log(config);
		$s('config',JSON.stringify(config));
	}

	function load_config(){
		try {
			var config=JSON.parse($g('config'));
			$('.'+spocklet+'_conf input[type=text]').each(function(){
				$(this).val(config[this.id.replace(spocklet,'')]);
			});
			$('.'+spocklet+'_conf input[type=checkbox]').each(function(){
				this.checked=config[this.id.replace(spocklet,'')];
			});
			$('.'+spocklet+'_conf select').each(function(){
				$(this).val(config[this.id.replace(spocklet,'')]);
			});
		} catch(dannhaltnicht) { }
	}

	function displayMafiaStats(){
		$('#'+spocklet+'_strength_stats').html('');
		$('#'+spocklet+'_strength_row').show();
        $('#'+spocklet+'_strength_stats').append(mafia_attack+' '+commas(stats.mafiaatt)+' (<span class="'+(stats.mafiaatt-stats.start_mafiaatt >= 0?'good">+':'bad">')+''+commas(stats.mafiaatt-stats.start_mafiaatt)+'</span>) ');
		$('#'+spocklet+'_strength_stats').append(mafia_defense+' '+commas(stats.mafiadef)+' (<span class="'+(stats.mafiadef-stats.start_mafiadef >= 0?'good">+':'bad">')+''+commas(stats.mafiadef-stats.start_mafiadef)+'</span>) ');

	}


	/******************** helper *********************/
	function loadStats(){
		getStats(function(){
			// save first stats
			stats.start_mafiaatt=stats.mafiaatt;
			stats.start_mafiadef=stats.mafiadef;
			displayMafiaStats();
			loadInventoryAAN();
		});
	}

	function loadInventoryAAN() {
		User.clicks++;
		var preurl = '//facebook.mafiawars.zynga.com/mwfb/remote/html_server.php?';
		var params = {
			'ajax': 1,
			'xw_client_id': 8,
			'liteload': 1,
			'sf_xw_user_id': User.id,
			'sf_xw_sig': local_xw_sig,
			'xw_city': 1,
			'clicks': User.clicks
		};
		$.ajax({
			type: "POST",
			url: preurl+'xw_controller=inventory&xw_action=view&from_controller=inventory',
			data: params,
			cache: false,
			success: function(response){
				//itemdatabase = {};
				var ZyngaItems = jQuery.parseJSON(/var Items = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
				worstitems = jQuery.parseJSON(/MW.WorstItemsModule.update\((\{.*\})\);/.exec(response)[1]);
				//Locations = jQuery.parseJSON(/var Locations = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
				for (x in ZyngaItems) {
					ZyngaItems[x].combined = parseInt(ZyngaItems[x].attack+ZyngaItems[x].defense);
					itemdatabase[ZyngaItems[x].id] = ZyngaItems[x]; //{quantity: ZyngaItems[x].quantity}
				}
				log('Inventory load complete.');
				//console.log(worstitems);
				//console.log(itemdatabase);

			},
			error: function(){
				log('<span class="bad">Inventory Load failed!</span>');
			}
		});
	}

	function getStats(handler) {
		request('xw_controller=propertyV2&xw_action=createData&xw_city=5&tmp=&cb=&xw_person='+User.id.substr(2)+'&mwcom=1&city=5&xw_client_id=8',function(msg){
			data = JSON.parse(msg);
			stats.mafiaatt=parseInt(data.fightbar.group_atk.replace(',',''));
			stats.mafiadef=parseInt(data.fightbar.group_def.replace(',',''));
			stats.stam=parseInt(data.user_fields.user_max_stamina);
			stats.worstitems=data.worstitems;
			if(handler) { handler(); }
		});
	}

	function min(a,b){
		return a<b?a:b;
	}
	function max(a,b){
		return a>b?a:b;
	}
	function imgurl(img,w,h,a) {
		return '<img src="http://mwfb.static.zgncdn.com/mwfb/graphics/'+img+'" width="'+w+'" height="'+h+'" title="'+a+'" alt="'+a+'" align="absmiddle">';
	}
	function commas(s) {
		while (d=/(-)?(\d+)(\d{3}.*)/.exec(s)) {
			s = (d[1]?d[1]+d[2]+','+d[3]:d[2]+','+d[3]);
		}
		return s;
	}
	function unix_timestamp() {
		return parseInt(new Date().getTime().toString().substring(0, 10));
	}
	function compare(a,b) {
		if (a==b) { return 0; }
		if (a>b) { return -1; }
		return 1;
	}


	function timestamp(sec) {
		now = new Date();
		var CurH = now.getHours();
		CurH = (CurH<10?'0'+CurH:CurH);
		var CurM = now.getMinutes();
		CurM = (CurM<10?'0'+CurM:CurM);
		var CurS = now.getSeconds();
		CurS = (CurS<10?'0'+CurS:CurS);
		if(sec) {
			return '<span class="more_in">['+CurH+':'+CurM+':'+CurS+']</span> ';
		} else {
			return '<span class="more_in">['+CurH+':'+CurM+']</span> ';
		}
	}

	function log(message){
		message='<span class="more_in">'+timestamp()+'</span> '+message;
		logs.unshift(message);
		showlog();
	}
	function debuglog(message){
		message='<span class="more_in">'+timestamp(true)+'</span> '+message;
		debuglogs.unshift(message);
		if(debuglogs.length>10) { debuglogs.pop(); }
		$e('debug').html(debuglogs.join('<br />'));
	}

	function $e(element) {
		return $('#'+spocklet+'_'+element);
	}
	function $i(element) {
		return 'id="'+spocklet+'_'+element+'"';
	}
	function $c(element) {
		return 'class="'+spocklet+'_'+element+'"';
	}
	function $s(name,value) {
		storage.setItem(spocklet+'_'+name+'_'+User.trackId, value);
	}
	function $g(name) {
		return storage.getItem(spocklet+'_'+name+'_'+User.trackId);
	}
	function $b(name,text,color,mouseover) {
		if(!color) { color="black"; }
		if(!mouseover) { mouseover = text; }
		return '<a href="#" id="'+spocklet+'_'+name+'" class="sexy_button_new short '+color+'" title="'+mouseover+'"><span><span>'+text+'</span></span></a>';
	}
	// by Eike
	String.prototype.re = function(regex){
		var r=new RegExp(regex);
		var m;
		if(m=r.exec(this)) {
			return m[1];
		} else {
			return '';
		}
	}
	function showlog(){
		var displaylogs=logs.slice(0,loglines);
		var footer = logs.length>0?'<br /><a href="#" '+$i('logs_more')+' title="Show 5 more lines">more</a> <a href="#" '+$i('logs_less')+' title="Show 5 less lines">less</a> <a href="#" '+$i('logs_clear')+' title="Clear log">clear</a>':'';
		$('#'+spocklet+'_log').html(displaylogs.join('<br />')+footer);
		$e('logs_more').click(function(){ loglines+=5; showlog(); return false;});
		$e('logs_less').click(function(){ loglines-=5; showlog(); return false;});
		$e('logs_clear').click(function(){ logs=[]; showlog(); return false;});
	}
	function request(url, handler, errorhandler) {
		var timestamp = parseInt(new Date().getTime().toString().substring(0, 10));
		if (url.indexOf('cb=') == -1) {
			url += '&cb='+User.id+timestamp;
		}
		if (url.indexOf('tmp=') == -1) {
			url += '&tmp='+timestamp;
		}
		User.clicks++;
		var preurl = '//facebook.mafiawars.zynga.com/mwfb/remote/html_server.php?';
		var params = {
			'ajax': 1,
			'liteload': 1,
			'sf_xw_user_id': User.id,
			'sf_xw_sig': local_xw_sig,
			'xw_client_id': 8,
			'skip_req_frame': 1,
			'clicks': User.clicks
		};
		$.ajax({
			type: "POST",
			url: preurl+url,
			data: params,
			cache: false,
			success: handler,
			error: errorhandler
		});
	}

	//add analytics
	function loadContent(file){
		var head = document.getElementsByTagName('head').item(0);
		var scriptTag = document.getElementById('loadScript');
		if(scriptTag) head.removeChild(scriptTag);
			script = document.createElement('script');
			script.src = file;
			script.type = 'text/javascript';
			script.id = 'loadScript';
			head.appendChild(script);
	}
	loadContent('https://www.google-analytics.com/ga.js');
	try {
		var pageTracker = _gat._getTracker("UA-8435065-3");
		pageTracker._trackPageview();
		pageTracker._trackPageview("/script/"+spocklet);
	}
	catch(err) {}
	//end analytics
})()
